const app = getApp()
import axios from '../../utils/axios';

Page({

  data: {
    navList: [{
      logo: '../../image/index/dog-people.png',
      name: '汪星人'
    }, {
      logo: '../../image/index/cat-people.png',
      name: '喵星人'
    }, {
      logo: '../../image/index/brand-house.png',
      name: '品牌屋'
    }],
    navCoupon: {
      name: "领劵中心",
      logo: '../../image/index/index-coupon.png',
      id: "coupon"
    },
    pageIndex: 1,
    discountsList: [], // 特价商品
    commodityList: [], // 推荐好物
    couponList: [], // 优惠券
    bannerList: [], // 轮播图list
    featrueBrandList: [], // 品牌专题
    featrueActivityList: [], // 活动专题
    key: "", // 如果key有值，说明是扫拉新二维码进来的
    classifyIndex: 0,
    commodityInfo: {},
    shopp: false,
  },

  onLoad: function (options) {

    console.log("index的参数：", options)
    if (decodeURIComponent(options.key) != "undefined") {

      app.globalData.inviter = decodeURIComponent(options.key)

      wx.reLaunch({
        url: '/pages/login/login',
      })

    }

    this.selectFeature()
    this.recommendGoods()
    this.selectActivityFeature()
    this.getBannerList()
  },

  onShow: function () {

    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      // shoppCountFlag为true时，说明有物品被加入购物车，需要重新刷新数量
      if (app.globalData.shoppCountFlag) {
        app.globalData.shoppCountFlag = false
        axios('/groupon/goodsCart').then(res => {
          if (res.data.resultcode == 1) {
            app.globalData.shoppCount = res.data.num
            this.getTabBar().setData({
              shoppCount: res.data.num
            })
          }
        })
      } else {
        this.getTabBar().setData({
          shoppCount: app.globalData.shoppCount
        })
      }
      this.getTabBar().setData({
        selected: 0
      })
    }

  },

  // 获取轮播图list
  getBannerList: function () {
    axios('/groupon/banner').then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {
        this.setData({
          bannerList: res.data.result
        })
      }
    })
  },

  // 查询品牌专题列表
  selectFeature: function () {
    axios("/groupon/feature", {
      type: 1
    }).then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {
        this.setData({
          featrueBrandList: res.data.result
        })
      }
    })
  },

  // 查询活动专题列表
  selectActivityFeature: function () {
    axios("/groupon/feature", {
      type: 2
    }).then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {
        this.setData({
          featrueActivityList: res.data.result
        })
      }
    })
  },

  // 事件委托
  getUserInfo: function (e) {

    // 当接口返回‘请登录’时，showLogin就变为true，然后调用授权
    if (e.detail.userInfo && app.globalData.showLogin) {
      const self = this
      app.signin(e.detail, function (res) {
        app.globalData.showLogin = false
        wx.navigateTo({
          url: '/pages/uifoncoupon/uifoncoupon',
        })
      })
    }

  },

  // 查询优惠券
  coupons: function () {
    axios('/cloud/coupons', {
      store_id: app.globalData.storeId
    }).then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {
        this.setData({
          couponList: app.disposeList(res.data.result.store)
        })
      }
    })
  },

  // 查询推荐好物商品
  recommendGoods: function () {
    axios('/groupon/today', {
      page: this.data.pageIndex
    }).then(res => {
      if (res.data.resultcode == 1) {
        let list = res.data.result
        for (let i = 0; i < list.length; i++) {
          if (list[i].atlas.length == 0) {
            list[i].atlas = [{
              image: list[i].image
            }]
          }
          list[i]['name'] = list[i].title
        }
        this.setData({
          commodityList: this.data.commodityList.concat(app.disposeList(list))
        })
      }
    })
  },

  // 查询导航列表
  recommendGoodsType: function () {
    axios('/cloud/recommendGoodsType', {
      store_id: app.globalData.storeId
    }).then(res => {
      console.log(res)
      if (res.data.resultcode == 1) {
        let itemJson = {
          name: "品牌屋",
          logo: '../../image/index/brand-house.png',
          id: "brand"
        }
        res.data.result.push(itemJson)
        this.setData({
          navList: res.data.result
        })
      }
    })
  },

  // 点击购买
  shoppBuy: function (e) {
    let goodsId = e.currentTarget.dataset.goodsid

    for (let i = 0; i < this.data.commodityList.length; i++) {
      if (this.data.commodityList[i].goods_id == goodsId) {

        // 无规格，则给一个通用
        if (this.data.commodityList[i].attach == undefined || this.data.commodityList[i].attach.length <= 0) {
          let param = [{
            attach_id: '-1',
            name: '通用',
            discount: 0,
            price: this.data.commodityList[i].showMoney,
            showMoney: this.data.commodityList[i].showMoney,
            showSave: parseFloat(this.data.commodityInfo[i].showSave).toFixed(2),
            stock: this.data.commodityList[i].stock
          }]
          this.data.commodityList[i]['attach'] = param
          this.setData({
            classifyIndex: 0,
            commodityInfo: this.data.commodityList[i],
            shopp: true
          })
        } else {
          for (let j = 0; j < this.data.commodityList[i].attach.length; j++) {
            let itemAttach = this.data.commodityList[i].attach[j]
            itemAttach['showMoney'] = itemAttach.discount > 0.01 ? itemAttach.discount : itemAttach.price
            itemAttach['showSave'] = parseFloat(itemAttach.price - itemAttach.showMoney).toFixed(2)
          }
          this.setData({
            classifyIndex: 0,
            commodityInfo: this.data.commodityList[i],
            shopp: true
          })
        }
      }
    }

  },

  // 跳转商品详情
  checkDetails: function (e) {
    let goodsId = e.currentTarget.dataset.goodsid
    wx.navigateTo({
      url: '/pages/details/details?goodsId=' + goodsId
    })
  },

  // 跳转到品牌专场
  checkBrand: function (e) {
    for (let i = 0; i < this.data.featrueBrandList.length; i++) {
      if (this.data.featrueBrandList[i].feature_id == e.currentTarget.dataset.id) {
        app.globalData.brandImage = this.data.featrueBrandList[i].image
      }
    }
    wx.navigateTo({
      url: '/pages/brand/brand?brandId=' + e.currentTarget.dataset.id
    })
  },

  // 跳转到活动专场
  checkActivity: function (e) {
    for (let i = 0; i < this.data.featrueActivityList.length; i++) {
      if (this.data.featrueActivityList[i].feature_id == e.currentTarget.dataset.id) {
        app.globalData.brandImage = this.data.featrueActivityList[i].image
      }
    }
    wx.navigateTo({
      url: '/pages/brand/brand?brandId=' + e.currentTarget.dataset.id
    })
  },

  // 跳转到优惠券页面
  checkCoupon: function (e) {
    if (app.globalData.userToken == '' || app.globalData.showLogin) {
      app.globalData.showLogin = true
    } else {
      wx.navigateTo({
        url: '/pages/uifoncoupon/uifoncoupon',
      })
    }

  },

  // 跳转到商品页面
  checkCommodity: function (e) {
    console.log(e)
    app.globalData.checkNav = e.currentTarget.dataset.typename
    app.globalData.checkFlag = true
    wx.switchTab({
      url: '/pages/allCommodity/allCommodity'
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("上拉触底")
    ++this.data.pageIndex
    this.recommendGoods()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "每日劲爆商品等您光顾，众多宠物用品、超大优惠等你来！"
    }
  }

})